import React, { useState ,useCallback,useMemo} from "react";

export default function App() {
    const[name,setName]=useState('liaoziqiao')
  const [text, setText] = useState("");
  const [list, setList] = useState(["初始", "dwd"]);
  const handleChange =useCallback(
    (evt) => {
        console.log("handleChangehandleChange", evt.target.value);
        setText(evt.target.value);
      },[]
  )
  
  //useCallback防止因为组件重新渲染，导致方法背重新创建，起到缓存作用。在第二个参数里声明相关的依赖，只有相关的变化看才重新声明。不然永远都是旧的
  //useMemo 会执行第一个函数且将函数执行结果返回给你
  //useMemo更适合经过函数计算得到一个确定的值
  const rand1 = Math.floor(Math.random() * 999999 + 1);
  const handleAdd = useCallback(
    () => {
        console.log("dawdawd输入值", text, list);
        let findeIndex = list.findIndex((item) => {
          return text === item;
        });
        if (findeIndex !== -1) {
          setText("");
          alert("输入值已存在，请重新输入！");
          return;
        }
        if (text.trim() === "") {
          setText("");
          alert("不能输入空格值，请重新输入！");
          return;
        }
        setList([...list, text]);
        // 输入完清空输入框值
        setText("")
      },
    [list,text],
  )
  
  const handleDelete =useMemo(
   ()=> (i) => {
        console.log("能删除的下标", i);
        // 不能影响原状态
        var newList = [...list];
        newList.splice(i, 1);
        setList([...newList])
      },
    [list],
  )
  
  return (
    <div>
        {name}-<button onClick={()=>{
            setName('廖子乔更新')
        }}>change_name</button>

        <span>         

        </span>
      <input onChange={handleChange} value={text} />
      <button onClick={handleAdd}>添加</button>

      <ul>
        {list.map((item, index) => (
          <li key={item + rand1}>
            {item}{" "}
            <button
              onClick={() => {
                handleDelete(index);
              }}
            >
              删除Del
            </button>
          </li>
        ))}
      </ul>
      {list.length > 0 ? <span>list数据如上</span> : <h4>暂无待办事项</h4>}
    </div>
  );
}
